package org.feng.navigation.generator.definition;

import lombok.Getter;
import lombok.NonNull;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 枚举内容<br>
 * 例如：CHONG_WU_XIN_WEN("46", "宠物新闻", "宠物及相关产业新闻资讯")
 *
 * @version v1.0
 * @author: junzi
 * @date: 2023年02月07日 23时22分
 */
public class EnumFileContentDefinition {
    @Getter
    private final String key;
    private final List<String> contents;

    @Getter
    private final String originChineseBody;

    public EnumFileContentDefinition(@NonNull String key, List<String> contents) {
        this.key = key;
        this.contents = contents;
        this.originChineseBody = contents.get(0);
    }

    public String getPinYinEnumName() {
        String pinYinToEnumName = EnumFileContentDefinition.pinYinToEnumName(toPinYin(originChineseBody));
        List<String> allParams = new ArrayList<>();
        allParams.add(this.key);
        allParams.addAll(contents);
        return allParams.stream().collect(Collectors.joining("\", \"", pinYinToEnumName + "(\"", "\")"));
    }

    /**
     * 将拼音转换为枚举名，并只包含大写字母和下划线
     *
     * @param pinYin 拼音
     * @return 枚举名，比如  <code>pin1duo1duo1</code> 转换为 <code>PIN_DUO_DUO</code>
     */
    public static String pinYinToEnumName(String pinYin) {
        // 替换声调为下划线
        pinYin = pinYin.replaceAll("[1-5]", "_");
        // 摘出字母、下划线（过滤特殊字符）
        String regEx = "[A-Za-z_]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(pinYin);

        StringBuilder sb = new StringBuilder();
        while (m.find()) {
            sb.append(m.group().toUpperCase(Locale.ROOT));
        }
        return sb.substring(0, sb.length() - 1);
    }

    /**
     * 将中文汉字转换成拼音（带有音调，数字1对应一声，数字2对应二声，数字3对应三声，数字4对应四声）
     *
     * @param chinese 中文汉字，比如 “拼多多”
     * @return 拼音，比如 “拼多多” 会转换为 <code>pin1duo1duo1</code>
     */
    public static String toPinYin(String chinese) {
        try {
            return PinyinHelper.toHanYuPinyinString(chinese);
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            throw new IllegalArgumentException(e);
        }
    }
}